package org.dxy.controller;

import org.dxy.entity.Trip;
import org.dxy.service.TripService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

// 车次控制器
@RestController("tripController")
public class TripController {
    @Autowired
    private TripService tripService;

    @GetMapping("/addTrip")
    public String showAddTripPage() {
        return "add_trip";
    }

    @PostMapping("/addTrip")
    public String addTrip(@ModelAttribute Trip trip, Model model) {
        try {
            Trip addedTrip = tripService.addTrip(trip);
            model.addAttribute("message", "车次添加成功");
            return "trip_list";
        } catch (Exception e) {
            model.addAttribute("error", "车次添加失败：" + e.getMessage());
            return "add_trip";
        }
    }

    @GetMapping("/editTrip/{id}")
    public String showEditTripPage(@PathVariable Long id, Model model) {
        Trip trip = tripService.getTripById(id);
        if (trip!= null) {
            model.addAttribute("trip", trip);
            return "edit_trip";
        } else {
            model.addAttribute("error", "车次不存在");
            return "trip_list";
        }
    }

    @PostMapping("/editTrip")
    public String editTrip(@ModelAttribute Trip trip, Model model) {
        try {
            Trip updatedTrip = tripService.updateTrip(trip);
            model.addAttribute("message", "车次更新成功");
            return "trip_list";
        } catch (Exception e) {
            model.addAttribute("error", "车次更新失败：" + e.getMessage());
            return "edit_trip";
        }
    }

    @GetMapping("/deleteTrip/{id}")
    public String deleteTrip(@PathVariable Long id, Model model) {
        try {
            tripService.deleteTrip(id);
            model.addAttribute("message", "车次删除成功");
            return "trip_list";
        } catch (Exception e) {
            model.addAttribute("error", "车次删除失败：" + e.getMessage());
            return "trip_list";
        }
    }

    @GetMapping("/searchTrips")
    public String searchTrips(@RequestParam String departure, @RequestParam String destination, @RequestParam LocalDateTime departureTime, Model model) {
        List<Trip> trips = tripService.searchTrips(departure, destination, departureTime);
        model.addAttribute("trips", trips);
        return "trip_search_results";
    }
}
